package vn.lumi.smarthome.ui.schedule;

import vn.lumi.smarthome.Config;
import vn.lumi.smarthome.LumiHome;
import vn.lumi.smarthome.R;
import vn.lumi.smarthome.io.database.DatabaseHelper;
import vn.lumi.smarthome.io.database.TBL_DeviceState;
import vn.lumi.smarthome.io.database.TBL_Schedule;
import vn.lumi.smarthome.io.model.Device;
import vn.lumi.smarthome.io.model.Schedule;
import vn.lumi.smarthome.io.model.Schedule.OnControlScheduleListener;
import vn.lumi.smarthome.service.VibrateThread;
import vn.lumi.smarthome.ui.base.BaseFragment;
import vn.lumi.smarthome.ui.base.MainFragment;
import vn.lumi.smarthome.ui.base.TextViewCustom;
import vn.lumi.smarthome.ui.scene.AbstractSceneFragment;
import vn.lumi.smarthome.ulti.ChangeFont;
import vn.lumi.smarthome.ulti.Preference;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.CursorAdapter;
import android.util.Log;
import android.util.SparseIntArray;
import android.view.ContextThemeWrapper;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

public class ScheduleListFragment extends BaseFragment implements
		LoaderCallbacks<Cursor>, OnControlScheduleListener, OnClickListener {

	// private static final String TAG = "ScheduleListActivity";
	private ListView mListSchedules;

	private ScheduleAdapter mScheduleAdapter;

	private int deviceId = 0;
	// private int roomId = 0;
	private String deviceName = "";
	private int deviceType;

	LinearLayout layoutActionbar;
	private Button btn_edit;
	private Button btn_add;
	private Button btn_back;
	TextViewCustom tv_title;
	int colorForward;
	private static ScheduleListFragment scheduleListFragment;

	public static boolean isEdit = false;

	// Khai bao ID cua Loader
	private static final int LOADER_ID = 10;

	public static final String EXTRA_DEVICE_ID = "device_id";
	public static final String EXTRA_DEVICE_NAME = "device_name";
	public static final String EXTRA_DEVICE_TYPE = "device type";
	public static final String EXTRA_ROOM_ID = "room_id";
	public static final String EXTRA_COLOR = "color";
	public static final String MENU_FRAGMENT = "menu";

	public static final String DEVICE_ID = "device id";

	public static ScheduleListFragment newInstance(int deviceId,
			String deviceName, int deviceType, int roomId, int floorId,
			int colorForward, String nameRoom, String nameFoor) {
		if (scheduleListFragment == null) {
			scheduleListFragment = new ScheduleListFragment();
		}
		Bundle bundle = new Bundle();
		bundle.putInt(EXTRA_DEVICE_ID, deviceId);
		bundle.putString(EXTRA_DEVICE_NAME, deviceName);
		bundle.putInt(EXTRA_DEVICE_TYPE, deviceType);
		bundle.putInt(EXTRA_ROOM_ID, roomId);
		bundle.putInt(EXTRA_COLOR, colorForward);
		bundle.putString(MainFragment.NAME_ROOM, nameRoom);
		bundle.putString(MainFragment.NAME_FLOOR, nameFoor);
		bundle.putInt(MainFragment.FLOOR_ID, floorId);
		scheduleListFragment.setArguments(bundle);
		return scheduleListFragment;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		Config.configLanguage(getActivity().getBaseContext(),
				Preference.getLanguage(getActivity().getApplicationContext()));// Thiet lap
		// ngon ngu

		deviceId = getArguments().getInt(EXTRA_DEVICE_ID, -1);
		deviceName = getArguments().getString(EXTRA_DEVICE_NAME);
		deviceType = getArguments().getInt(EXTRA_DEVICE_TYPE, -1);
		mRoom_id = getArguments().getInt(EXTRA_ROOM_ID, -1);
		mFloor_id = getArguments().getInt(MainFragment.FLOOR_ID, -1);
		colorForward = getArguments().getInt(EXTRA_COLOR, -1);
		nameRoom = getArguments().getString(MainFragment.NAME_ROOM);
		nameFloor = getArguments().getString(MainFragment.NAME_FLOOR);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View view = inflater.inflate(R.layout.activity_schedule_list_fragment,
				container, false);
		setupActionBar(view);
		init_view(view);
		init_data();
		init_loader();
		return view;

	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		tv_title.setText(getString(R.string.txt_schedule_device) + deviceName);
	}

	@Override
	public void onAttach(Activity activity) {
		// TODO Auto-generated method stub
		super.onAttach(activity);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.actionbar_schedule_list_add:
			if (Config.isVibrate)
				new VibrateThread(getActivity().getApplicationContext())
						.start();
			if (mScheduleAdapter.getCount() < 3) {
				// Intent i = new Intent(getActivity(), AddScheduleActivity.class);
				// i.putExtra(AddScheduleActivity.EXTRA_DEVICE_ID, deviceId);
				// i.putExtra(AddScheduleActivity.EXTRA_DEVICE_NAME, deviceName);
				// i.putExtra(AddScheduleActivity.EXTRA_DEVICE_TYPE, deviceType);
				// i.putExtra(AddScheduleActivity.EXTRA_COLOR, colorForward);
				// startActivity(i);
				FragmentManager fragmentManager = getActivity()
						.getSupportFragmentManager();
				FragmentTransaction transaction = fragmentManager
						.beginTransaction();
				AddScheduleFragment addScheduleFragment = AddScheduleFragment
						.newInstance(deviceId, deviceName, deviceType,
								colorForward);
				transaction.replace(R.id.activity_main_content,
						addScheduleFragment,
						AddScheduleFragment.ADDSCHEDULEFRAGMENT);
				transaction.addToBackStack(null);
				transaction.setCustomAnimations(
						R.animator.fragment_slide_left_enter,
						R.animator.fragment_slide_left_exit,
						R.animator.fragment_slide_right_enter,
						R.animator.fragment_slide_right_exit);

				// Commit the transaction
				transaction.commit();
			} else {
				showCustomDialog(R.string.txt_error, R.string.txt_max_schedules);
			}
			break;

		case R.id.actionbar_schedule_list_edit:
			if (Config.isVibrate)
				new VibrateThread(getActivity().getApplicationContext())
						.start();
			if (isEdit) {
				btn_edit.setBackgroundDrawable(getResources().getDrawable(
						R.drawable.img_editscene_selector));
				isEdit = false;
				// refresh lisview
				restart_loader();
			} else {
				btn_edit.setBackgroundDrawable(getResources().getDrawable(
						R.drawable.img_ok));
				isEdit = true;
				// refresh lisview
				restart_loader();
			}
			break;
		default:
			break;
		}
	}

	public static void setMode(boolean mode) {
		isEdit = mode;
	}

	/**
	 * @return: true: edit
	 * 
	 */
	public static boolean getMode() {
		return isEdit;
	}

	// -----------------------------Actionbar------------------
	private void setupActionBar(View view) {
		tv_title = (TextViewCustom) view
				.findViewById(R.id.actionbar_schedule_list_title);
		tv_title.setText(getString(R.string.txt_schedule_device) + deviceName);
		btn_add = (Button) view.findViewById(R.id.actionbar_schedule_list_add);
		btn_add.setOnClickListener(this);
		btn_edit = (Button) view
				.findViewById(R.id.actionbar_schedule_list_edit);
		btn_edit.setOnClickListener(this);
		setMode(false);

	}

	private void init_view(View view) {
		mListSchedules = (ListView) view
				.findViewById(R.id.activity_schedule_list_schedule);

		mScheduleAdapter = new ScheduleAdapter(getActivity(), null,
				CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
		mScheduleAdapter.initData(deviceId, deviceName);
		mScheduleAdapter.setControlSchedule(this);
		mListSchedules.setAdapter(mScheduleAdapter);
		btn_back = (Button) view
				.findViewById(R.id.actionbar_schedule_list_back);
		btn_back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				MainFragment mainFragment = MainFragment.newInstance(mFloor_id,
						mRoom_id, MainFragment.SCREEN_DEVICE, nameRoom,
						nameFloor);
				FragmentTransaction transaction = getActivity()
						.getSupportFragmentManager().beginTransaction();
				transaction.replace(R.id.activity_main_content, mainFragment,
						"main");
				transaction.setCustomAnimations(
						R.animator.fragment_slide_left_enter,
						R.animator.fragment_slide_left_exit,
						R.animator.fragment_slide_right_enter,
						R.animator.fragment_slide_right_exit);
				// Commit the transaction
				transaction.commit();
			}
		});
	}

	private void init_data() {

	}

	// @Override
	// public void finish() {
	// // TODO Auto-generated method stub
	// Intent intentMainActivity = new Intent();
	// intentMainActivity.putExtra(MainActivity.STRING_ANOTHER_REQUEST, true);
	// intentMainActivity.putExtra("RoomID", roomId);
	// setResult(RESULT_OK, intentMainActivity);
	// super.finish();
	// if (Config.isVibrate)
	// new VibrateThread(getApplicationContext()).start();
	// }

	private void init_loader() {
		Bundle bundle = new Bundle();
		bundle.putInt(DEVICE_ID, deviceId);
		getLoaderManager().initLoader(LOADER_ID, bundle, this);
	}

	private void restart_loader() {
		Bundle bundle = new Bundle();
		bundle.putInt(DEVICE_ID, deviceId);
		getLoaderManager().restartLoader(LOADER_ID, bundle, this);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.LoaderManager.LoaderCallbacks#onCreateLoader(int, android.os.Bundle)
	 */
	@Override
	public Loader<Cursor> onCreateLoader(int id, Bundle bundle) {
		// TODO Auto-generated method stub
		int device_id = bundle.getInt(DEVICE_ID);
		String selection = TBL_Schedule.DEVICE_ID + "=?";
		String[] selectionArgs = new String[] { device_id + "" };
		return new CursorLoader(getActivity(),
				TBL_Schedule.CONTENT_URI_SCHEDULE, null, selection,
				selectionArgs, null);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.LoaderManager.LoaderCallbacks#onLoadFinished(android.content .Loader,
	 * java.lang.Object)
	 */
	@Override
	public void onLoadFinished(Loader<Cursor> arg0, Cursor arg1) {
		// TODO Auto-generated method stub
		mScheduleAdapter.swapCursor(arg1);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.LoaderManager.LoaderCallbacks#onLoaderReset(android.content .Loader)
	 */
	@Override
	public void onLoaderReset(Loader<Cursor> arg0) {
		// TODO Auto-generated method stub
		mScheduleAdapter.swapCursor(null);
	}

	private class ScheduleAdapter extends CursorAdapter {
		int deviceId = 0;
		String deviceName = "";
		SparseIntArray MapColorCurrent = new SparseIntArray();
		Context mContext;

		private static final String TAG = "SceneAdapter";

		private OnControlScheduleListener mOnControlScheduleListener;

		public ScheduleAdapter(Context context, Cursor c, int flags) {
			super(context, c, flags);
			mContext = context;
		}

		public void initData(int deviceId, String name) {
			this.deviceId = deviceId;
			this.deviceName = name;
		}

		public void setControlSchedule(
				OnControlScheduleListener onControlScheduleListener) {
			this.mOnControlScheduleListener = onControlScheduleListener;
		}

		@Override
		public void bindView(View view, final Context context, Cursor cursor) {

			TextViewCustom img_tv_schedule_on;
			TextViewCustom img_tv_schedule_off;
			ImageView imv_schedule_on = null;
			// ImageView imv_schedule_off = null;

			LinearLayout scheduleDescription = (LinearLayout) view
					.findViewById(R.id.item_listview_schedule_name);
			LinearLayout linear_schedule_on = (LinearLayout) view
					.findViewById(R.id.item_listview_schedule_linear_schedule_on);
			LinearLayout linear_schedule_off = (LinearLayout) view
					.findViewById(R.id.item_listview_schedule_linear_schedule_off);

			// state image onclick
			final int scheduleId = cursor.getInt(cursor
					.getColumnIndex(TBL_Schedule._ID));

			if (deviceType == Device.DEVICE_TYPE_LIGHT) {
				// Khong can thiet vi khong lam gi o 2 textview nay
				// img_tv_schedule_on = (TextViewCustom) view
				// .findViewById(R.id.item_listview_schedule_img_tv_on);
				// img_tv_schedule_off = (TextViewCustom) view
				// .findViewById(R.id.item_listview_schedule_img_tv_off);
			} else if (deviceType == Device.DEVICE_TYPE_GATE) {
				img_tv_schedule_on = (TextViewCustom) view
						.findViewById(R.id.item_listview_schedule_img_tv_on);
				img_tv_schedule_off = (TextViewCustom) view
						.findViewById(R.id.item_listview_schedule_img_tv_off);
				img_tv_schedule_on
						.setBackgroundResource(R.drawable.ic_gate_8);
				img_tv_schedule_on.setText("");

				img_tv_schedule_off
						.setBackgroundResource(R.drawable.ic_gate_1);
				img_tv_schedule_off.setText("");
			} else if (deviceType == Device.DEVICE_TYPE_MULTIROOM_AUDIO) {
				img_tv_schedule_on = (TextViewCustom) view
						.findViewById(R.id.item_listview_schedule_img_tv_on);
				img_tv_schedule_off = (TextViewCustom) view
						.findViewById(R.id.item_listview_schedule_img_tv_off);
				img_tv_schedule_on
						.setBackgroundResource(R.drawable.img_multiroom_audio_on_selector);
				img_tv_schedule_on.setText("");

				img_tv_schedule_off
						.setBackgroundResource(R.drawable.img_multiroom_audio_off_selector);
				img_tv_schedule_off.setText("");
			} else if (deviceType == Device.DEVICE_TYPE_HOR_BLIND) {
				img_tv_schedule_on = (TextViewCustom) view
						.findViewById(R.id.item_listview_schedule_img_tv_on);
				img_tv_schedule_off = (TextViewCustom) view
						.findViewById(R.id.item_listview_schedule_img_tv_off);
				img_tv_schedule_on
						.setBackgroundResource(R.drawable.ic_hor_blind_8);
				img_tv_schedule_on.setText("");

				img_tv_schedule_off
						.setBackgroundResource(R.drawable.ic_hor_blind_1);
				img_tv_schedule_off.setText("");
			} else if (deviceType == Device.DEVICE_TYPE_VER_BLIND) {
				img_tv_schedule_on = (TextViewCustom) view
						.findViewById(R.id.item_listview_schedule_img_tv_on);
				img_tv_schedule_off = (TextViewCustom) view
						.findViewById(R.id.item_listview_schedule_img_tv_off);
				img_tv_schedule_on
						.setBackgroundResource(R.drawable.ic_ver_blind_8);
				img_tv_schedule_on.setText("");

				img_tv_schedule_off
						.setBackgroundResource(R.drawable.ic_ver_blind_1);
				img_tv_schedule_off.setText("");
			} else if (deviceType == Device.DEVICE_TYPE_RGB) {

				imv_schedule_on = (ImageView) view
						.findViewById(R.id.item_listview_schedule_imv_on);

				// Lay state_id
				int state_id = cursor.getInt(cursor
						.getColumnIndex(TBL_Schedule.STATE_ID));

				// Truy van den bang TBL_DEVICE_STATE lay trang thai cua led rgb thong qua colum
				// value
				String[] projection = { TBL_DeviceState.RGB };
				String selection = DatabaseHelper.DB_TBL_DEVICE_STATE + "."
						+ TBL_DeviceState._ID + "=?";
				String[] selectionArgs = new String[] { state_id + "" };
				Cursor cursorDeviceState = getActivity().getContentResolver()
						.query(TBL_DeviceState.CONTENT_URI_DEVICE_STATE,
								projection, selection, selectionArgs, null);
				if (cursorDeviceState != null) {
					if (cursorDeviceState.getCount() > 0) {
						cursorDeviceState.moveToFirst();

						int ColorCurrent;
						ColorCurrent = cursorDeviceState
								.getInt(cursorDeviceState
										.getColumnIndex(TBL_DeviceState.RGB));
						MapColorCurrent.put(scheduleId, ColorCurrent);
						imv_schedule_on
								.setBackgroundColor(ColorCurrent + 0xFF000000);

					}
					cursorDeviceState.close();
					cursorDeviceState = null;
				}

			}

			TextViewCustom tv_schedule_on = (TextViewCustom) view
					.findViewById(R.id.item_listview_schedule_on);

			TextViewCustom tv_schedule_off = (TextViewCustom) view
					.findViewById(R.id.item_listview_schedule_off);

			ImageView img_icon = (ImageView) view
					.findViewById(R.id.item_listview_schedule_name_icon);
			ImageView img_t2 = (ImageView) view
					.findViewById(R.id.item_listview_schedule_name_t2);
			ImageView img_t3 = (ImageView) view
					.findViewById(R.id.item_listview_schedule_name_t3);
			ImageView img_t4 = (ImageView) view
					.findViewById(R.id.item_listview_schedule_name_t4);
			ImageView img_t5 = (ImageView) view
					.findViewById(R.id.item_listview_schedule_name_t5);
			ImageView img_t6 = (ImageView) view
					.findViewById(R.id.item_listview_schedule_name_t6);
			ImageView img_t7 = (ImageView) view
					.findViewById(R.id.item_listview_schedule_name_t7);
			ImageView img_cn = (ImageView) view
					.findViewById(R.id.item_listview_schedule_name_cn);

			ImageView imgState = (ImageView) view
					.findViewById(R.id.item_listview_schedule_check);

			// // set name
			String timeOn = "";
			String timeOff = "";
			if (cursor.getInt(cursor.getColumnIndex(TBL_Schedule.HOUR)) > 24)
				// description += "\n" + "Giờ bật:Không bật";
				timeOn = "--:--";
			else
				timeOn = timeOn
						+ AbstractSceneFragment.padding_str(cursor
								.getInt(cursor
										.getColumnIndex(TBL_Schedule.HOUR)))
						+ ":"
						+ AbstractSceneFragment.padding_str(cursor
								.getInt(cursor
										.getColumnIndex(TBL_Schedule.MINUTE)));

			if (cursor.getInt(cursor.getColumnIndex(TBL_Schedule.HOUR_END)) == Schedule.SCHEDULE_NOT_TURNOFF_TYPE)
				// description += "\n" + "Giờ tắt:Không tắt" + "\n";
				timeOff = "--:--";
			else
				// description += "\n"
				// + "Giờ tắt: "
				timeOff = timeOff
						+ AbstractSceneFragment
								.padding_str(cursor.getInt(cursor
										.getColumnIndex(TBL_Schedule.HOUR_END)))
						+ ":"
						+ AbstractSceneFragment
								.padding_str(cursor.getInt(cursor
										.getColumnIndex(TBL_Schedule.MINUTE_END)));

			tv_schedule_on.setText(timeOn);
			tv_schedule_off.setText(timeOff);

			int repeat = cursor.getInt(cursor
					.getColumnIndex(TBL_Schedule.REPEAT));
			Log.e("repeat", "" + repeat);
			if (repeat == Schedule.SCHEDULE_REPEAT_ON) {
				img_icon.setImageResource(R.drawable.img_schedule_name_on);
				if (cursor.getInt((cursor.getColumnIndex(TBL_Schedule.MONDAY))) == Schedule.SCHEDULE_DAY_ON)
					img_t2.setImageResource(R.drawable.img_schedule_name_t2);
				else
					img_t2.setImageResource(R.drawable.img_schedule_name_off_t2);
				if (cursor
						.getInt((cursor.getColumnIndex(TBL_Schedule.TUESDAY))) == Schedule.SCHEDULE_DAY_ON)
					img_t3.setImageResource(R.drawable.img_schedule_name_t3);
				else
					img_t3.setImageResource(R.drawable.img_schedule_name_off_t3);
				if (cursor.getInt((cursor
						.getColumnIndex(TBL_Schedule.WEDNESDAY))) == Schedule.SCHEDULE_DAY_ON)
					img_t4.setImageResource(R.drawable.img_schedule_name_t4);
				else
					img_t4.setImageResource(R.drawable.img_schedule_name_off_t4);
				if (cursor
						.getInt((cursor.getColumnIndex(TBL_Schedule.THURSDAY))) == Schedule.SCHEDULE_DAY_ON)
					img_t5.setImageResource(R.drawable.img_schedule_name_t5);
				else
					img_t5.setImageResource(R.drawable.img_schedule_name_off_t5);
				if (cursor.getInt((cursor.getColumnIndex(TBL_Schedule.FRIDAY))) == Schedule.SCHEDULE_DAY_ON)
					img_t6.setImageResource(R.drawable.img_schedule_name_t6);
				else
					img_t6.setImageResource(R.drawable.img_schedule_name_off_t6);
				if (cursor
						.getInt((cursor.getColumnIndex(TBL_Schedule.SATURDAY))) == Schedule.SCHEDULE_DAY_ON)
					img_t7.setImageResource(R.drawable.img_schedule_name_t7);
				else
					img_t7.setImageResource(R.drawable.img_schedule_name_off_t7);
				if (cursor.getInt((cursor.getColumnIndex(TBL_Schedule.SUNDAY))) == Schedule.SCHEDULE_DAY_ON)
					img_cn.setImageResource(R.drawable.img_schedule_name_cn);
				else
					img_cn.setImageResource(R.drawable.img_schedule_name_off_cn);
			} else {
				img_icon.setImageResource(R.drawable.img_schedule_name_off);
				img_t2.setImageResource(R.drawable.img_schedule_name_off_t2);
				img_t3.setImageResource(R.drawable.img_schedule_name_off_t3);
				img_t4.setImageResource(R.drawable.img_schedule_name_off_t4);
				img_t5.setImageResource(R.drawable.img_schedule_name_off_t5);
				img_t6.setImageResource(R.drawable.img_schedule_name_off_t6);
				img_t7.setImageResource(R.drawable.img_schedule_name_off_t7);
				img_cn.setImageResource(R.drawable.img_schedule_name_off_cn);
			}
			// set state image
			final int state = cursor.getInt(cursor
					.getColumnIndex(TBL_Schedule.STATE));
			if (!getMode()) {

				if (state == Schedule.SCHEDULE_STATE_OFF) {
					imgState.setImageResource(R.drawable.img_tickoff);
				} else if (state == Schedule.SCHEDULE_STATE_ON) {
					imgState.setImageResource(R.drawable.img_tickon);
				}

			} else {
				// icon xoa lich
				imgState.setImageResource(R.drawable.img_scene_edit_delete);
			}

			imgState.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					if (Config.isVibrate)
						new VibrateThread(mContext).start();
					if (!getMode()) {
						if (state == Schedule.SCHEDULE_STATE_OFF) {
							// turn on schedule
							mOnControlScheduleListener
									.OnTurnOnSchedule(scheduleId);
							Log.d(TAG, "Turn on scheduleID = " + scheduleId);
						} else if (state == Schedule.SCHEDULE_STATE_ON) {
							// turn off schedule
							mOnControlScheduleListener
									.OnTurnOffSchedule(scheduleId);
							Log.d("SceneFragment", "Turn off scheduleID = "
									+ scheduleId);
						}
					} else {
						// // Xoa lich
						deleteSchedule(mContext, scheduleId, deviceId);

					}
				}

			});

			// config onclick --> edit schedule activity
			scheduleDescription.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					if (Config.isVibrate)
						new VibrateThread(mContext).start();
					if (getMode()) {
						// Intent intent = new Intent(context,
						// EditScheduleActivity.class);
						// intent.putExtra(EditScheduleActivity.EXTRA_SCHEDULE_ID,
						// scheduleId);
						// intent.putExtra(EditScheduleActivity.EXTRA_DEVICE_NAME,
						// deviceName);
						// intent.putExtra(EditScheduleActivity.EXTRA_DEVICE_ID,
						// deviceId);
						// intent.putExtra(EditScheduleActivity.EXTRA_DEVICE_TYPE,
						// deviceType);
						// intent.putExtra(EditScheduleActivity.EXTRA_COLOR,
						// MapColorCurrent.get(scheduleId));
						// context.startActivity(intent);
						forwardEditScheduleFragment(scheduleId);
					}
				}
			});
			linear_schedule_on.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					if (Config.isVibrate)
						new VibrateThread(mContext).start();
					if (getMode()) {
						// Intent intent = new Intent(context,
						// EditScheduleActivity.class);
						// intent.putExtra(EditScheduleActivity.EXTRA_SCHEDULE_ID,
						// scheduleId);
						// intent.putExtra(EditScheduleActivity.EXTRA_DEVICE_NAME,
						// deviceName);
						// intent.putExtra(EditScheduleActivity.EXTRA_DEVICE_ID,
						// deviceId);
						// intent.putExtra(EditScheduleActivity.EXTRA_DEVICE_TYPE,
						// deviceType);
						// intent.putExtra(EditScheduleActivity.EXTRA_COLOR,
						// MapColorCurrent.get(scheduleId));
						// context.startActivity(intent);
						forwardEditScheduleFragment(scheduleId);
					}
				}
			});
			linear_schedule_off.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					if (Config.isVibrate)
						new VibrateThread(mContext).start();
					if (getMode()) {
						// Intent intent = new Intent(context,
						// EditScheduleActivity.class);
						// intent.putExtra(EditScheduleActivity.EXTRA_SCHEDULE_ID,
						// scheduleId);
						// intent.putExtra(EditScheduleActivity.EXTRA_DEVICE_NAME,
						// deviceName);
						// intent.putExtra(EditScheduleActivity.EXTRA_DEVICE_ID,
						// deviceId);
						// intent.putExtra(EditScheduleActivity.EXTRA_DEVICE_TYPE,
						// deviceType);
						// intent.putExtra(EditScheduleActivity.EXTRA_COLOR,
						// MapColorCurrent.get(scheduleId));
						// context.startActivity(intent);
						forwardEditScheduleFragment(scheduleId);
					}
				}
			});

		}

		@Override
		public View newView(Context context, Cursor cursor, ViewGroup viewgroup) {
			if (deviceType == Device.DEVICE_TYPE_RGB) {
				return View.inflate(context,
						R.layout.item_listview_listschedule_rgb, null);
			}

			// Neu la rem or on/off
			else {
				return View.inflate(context,
						R.layout.item_listview_listschedule, null);
			}

		}

		public void forwardEditScheduleFragment(int scheduleId) {
			FragmentManager fragmentManager = getActivity()
					.getSupportFragmentManager();
			FragmentTransaction transaction = fragmentManager
					.beginTransaction();
			EditScheduleFragment editScheduleFragment = EditScheduleFragment
					.newInstance(deviceId, deviceName, deviceType,
							MapColorCurrent.get(scheduleId), scheduleId);

			transaction.replace(R.id.activity_main_content,
					editScheduleFragment,
					EditScheduleFragment.EDITSCHEDULEFRAGMENT);
			transaction.addToBackStack(null);
			transaction.setCustomAnimations(
					R.animator.fragment_slide_left_enter,
					R.animator.fragment_slide_left_exit,
					R.animator.fragment_slide_right_enter,
					R.animator.fragment_slide_right_exit);

			// Commit the transaction
			transaction.commit();
		}

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see vn.lumi.smarthome.io.model.Schedule.OnControlScheduleListener# OnTurnOnSchedule(int)
	 */
	@Override
	public void OnTurnOnSchedule(int scheduleId) {
		// TODO Auto-generated method stub
		ContentValues values = new ContentValues();
		values.put("scheduleId", scheduleId);
		getActivity().getContentResolver().update(
				TBL_Schedule.CONTENT_URI_SCHEDULE_TURN_ON, values, null, null);

		// show dialog
		ProgressDialog dialog = new ProgressDialog(new ContextThemeWrapper(
				getActivity(), R.style.AlertDialogCustom));
		dialog.setMessage(getString(R.string.txt_cotroling_device_in_HC));
		dialog.setCancelable(false);
		dialog.show();
		// Thay doi font chu cua Dialog
		ChangeFont changeFont = new ChangeFont(getActivity()
				.getApplicationContext());
		TextView textView = (TextView) dialog
				.findViewById(android.R.id.message);
		textView = changeFont.changeFontTextView(textView,
				R.string.txt_cotroling_device_in_HC, LumiHome.font, 16,
				Gravity.NO_GRAVITY,
				getResources().getColor(R.color.greenActionbar));

		// set broadcast receiver
		ToogleScheduleReceiver mReceiver = new ToogleScheduleReceiver(dialog);
		IntentFilter filter = new IntentFilter();
		filter.addAction(this
				.getString(R.string.txt_broadcast_Toogle_schedule_successful));
		filter.addAction(this
				.getString(R.string.txt_broadcast_Toogle_schedule_failed));
		getActivity().registerReceiver(mReceiver, filter);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see vn.lumi.smarthome.io.model.Schedule.OnControlScheduleListener# OnTurnOffSchedule(int)
	 */
	@Override
	public void OnTurnOffSchedule(int scheduleId) {
		// TODO Auto-generated method stub
		ContentValues values = new ContentValues();
		values.put("scheduleId", scheduleId);
		getActivity().getContentResolver().update(
				TBL_Schedule.CONTENT_URI_SCHEDULE_TURN_OFF, values, null, null);

		// show dialog
		ProgressDialog dialog = new ProgressDialog(new ContextThemeWrapper(
				getActivity(), R.style.AlertDialogCustom));
		dialog.setMessage(getString(R.string.txt_cotroling_device_in_HC));
		dialog.setCancelable(false);
		dialog.show();
		// Thay doi font chu cua Dialog
		ChangeFont changeFont = new ChangeFont(getActivity()
				.getApplicationContext());
		TextView textView = (TextView) dialog
				.findViewById(android.R.id.message);
		textView = changeFont.changeFontTextView(textView,
				R.string.txt_cotroling_device_in_HC, LumiHome.font, 16,
				Gravity.NO_GRAVITY,
				getResources().getColor(R.color.greenActionbar));

		// set broadcast receiver
		ToogleScheduleReceiver mReceiver = new ToogleScheduleReceiver(dialog);
		IntentFilter filter = new IntentFilter();
		filter.addAction(this
				.getString(R.string.txt_broadcast_Toogle_schedule_successful));
		filter.addAction(this
				.getString(R.string.txt_broadcast_Toogle_schedule_failed));
		getActivity().registerReceiver(mReceiver, filter);
	}

	public void deleteSchedule(Context mContext, int scheduleId, int deviceId) {
		ContentValues values = new ContentValues();
		values.put("Schedule id", scheduleId);
		values.put("device_id", deviceId);
		mContext.getContentResolver().update(
				TBL_Schedule.CONTENT_URI_SCHEDULE_DELETE, values, null, null);

		// show dialog
		ProgressDialog dialog = new ProgressDialog(new ContextThemeWrapper(
				mContext, R.style.AlertDialogCustom));
		dialog.setMessage(mContext
				.getString(R.string.txt_deleting_schedule_in_HC));
		dialog.setCancelable(false);
		dialog.show();
		// Thay doi font chu cua Dialog
		ChangeFont changeFont = new ChangeFont(mContext);
		TextView textView = (TextView) dialog
				.findViewById(android.R.id.message);
		textView = changeFont.changeFontTextView(textView,
				R.string.txt_deleting_schedule_in_HC, LumiHome.font, 16,
				Gravity.NO_GRAVITY,
				mContext.getResources().getColor(R.color.greenActionbar));

		// set broadcast receiver
		DeleteScheduleReceiver mReceiver = new DeleteScheduleReceiver(dialog);
		IntentFilter filter = new IntentFilter();
		filter.addAction(mContext
				.getString(R.string.txt_broadcast_del_schedule_sucessful));
		filter.addAction(mContext
				.getString(R.string.txt_broadcast_del_schedule_failed));
		mContext.registerReceiver(mReceiver, filter);
	}

	public class ToogleScheduleReceiver extends BroadcastReceiver {

		private ProgressDialog mDialog;

		public ToogleScheduleReceiver(ProgressDialog dialog) {
			mDialog = dialog;
		}

		@Override
		public void onReceive(Context context, Intent intent) {
			mDialog.cancel();
			getActivity().unregisterReceiver(this);

			if (intent
					.getAction()
					.equals(context
							.getString(R.string.txt_broadcast_Toogle_schedule_successful))) {

			}

			else if (intent
					.getAction()
					.equals(context
							.getString(R.string.txt_broadcast_Toogle_schedule_failed)))
				// displaySendFailed();
				showCustomDialog(R.string.txt_error,
						R.string.txt_error_cannot_connect_HC);

		}

	}

	public class DeleteScheduleReceiver extends BroadcastReceiver {

		private ProgressDialog mDialog;

		public DeleteScheduleReceiver(ProgressDialog dialog) {
			mDialog = dialog;
		}

		@Override
		public void onReceive(Context context, Intent intent) {
			mDialog.cancel();
			getActivity().unregisterReceiver(this);
			if (intent
					.getAction()
					.equals(context
							.getString(R.string.txt_broadcast_del_schedule_sucessful))) {

			}

			else if (intent
					.getAction()
					.equals(context
							.getString(R.string.txt_broadcast_del_schedule_failed)))
				// displayEditScheduleFailed();
				showCustomDialog(R.string.txt_error,
						R.string.txt_error_cannot_connect_HC);

		}

	}

	public void showCustomDialog(int title, int message) {
		AlertDialog.Builder ErrorDialog = new AlertDialog.Builder(
				new ContextThemeWrapper(getActivity(),
						R.style.AlertDialogCustom));

		ChangeFont changeFont = new ChangeFont(getActivity()
				.getApplicationContext());
		TextView tvTitle = new TextView(getActivity().getApplicationContext());
		tvTitle = changeFont.changeFontTextView(tvTitle, title,
				LumiHome.fontBold, LumiHome.sizeTittle, Gravity.CENTER,
				getResources().getColor(R.color.green));
		ErrorDialog.setCustomTitle(tvTitle);
		ErrorDialog.setMessage(message);
		ErrorDialog.setNegativeButton(R.string.glb_txt_return,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						if (Config.isVibrate)
							new VibrateThread(getActivity()
									.getApplicationContext()).start();
						dialog.cancel();
					}
				});
		AlertDialog alertErrorDialog = ErrorDialog.create();
		alertErrorDialog.show();
		alertErrorDialog.getWindow().getAttributes();
		TextView tvMessage = (TextView) alertErrorDialog
				.findViewById(android.R.id.message);
		tvMessage = changeFont.changeFontTextView(tvMessage, message,
				LumiHome.font, LumiHome.sizeContent, Gravity.NO_GRAVITY,
				getResources().getColor(R.color.greenLight));

		Button btn1 = alertErrorDialog
				.getButton(DialogInterface.BUTTON_NEGATIVE);
		btn1.setTypeface(Typeface.createFromAsset(getActivity().getAssets(),
				LumiHome.fontBold));
		btn1.setTextColor(getResources().getColor(R.color.greenActionbar));
		btn1.setTextSize(LumiHome.sizeButton);
	}

}
